package mytask.controller;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import mytask.dao.ProjectDAO;
import mytask.dao.ProjectMemberDAO;
import mytask.dao.TicketDAO;
import mytask.domain.AuthManager;
import mytask.model.Project;
import mytask.model.ProjectMember;
import mytask.model.Ticket;
import mytask.model.User;
import mytask.model.UserLogin;
import mytask.model.UserRole;
import mytask.view.Screen;
import mytask.view.ScreenManager;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;

@Controller
public final class HomeController extends MultiActionController {

    private static final int NUMBER_OF_TICKETS_TO_DISPLAY = 15;

    @Resource
    private TicketDAO ticketDAO;

    @Resource
    private ProjectMemberDAO memberDAO;

    @Resource
    private ProjectDAO projectDAO;

    public void setProjectMemberDAO(ProjectMemberDAO memberDAO) {
        this.memberDAO = memberDAO;
    }

    public void setTicketDAO(TicketDAO ticketDAO) {
        this.ticketDAO = ticketDAO;
    }

    public void setProjectDAO(ProjectDAO projectDAO) {
        this.projectDAO = projectDAO;
    }

    @RequestMapping(value = "/", method = RequestMethod.GET)
    public ModelAndView showWelcomeScreen() {
        if (AuthManager.isUserLoggedIn()) {
            return getWelcomeScreenForUser();
        }

        return getWelcomeScreenForGuest();
    }

    private ModelAndView getWelcomeScreenForUser() {
        final User user = AuthManager.getPageUser();

        final ModelAndView screen = ScreenManager.get(Screen.HOME_USER);

        final List<Project> projects = new ArrayList<Project>();
        final List<ProjectMember> members = memberDAO.listProjectMembers(user, UserRole.WAITING);
        for (int i = 0; i < members.size(); i++) {
            projects.add(members.get(i).getProject());
        }

        screen.addObject("projectInvitations", projects);

        final List<Project> myProjects = projectDAO.listAcceptedProjects(user, NUMBER_OF_TICKETS_TO_DISPLAY);
        screen.addObject("myProjects", myProjects);

        final List<Ticket> myTickets = ticketDAO.listTicketsFromAcceptedProjects(user, myProjects, NUMBER_OF_TICKETS_TO_DISPLAY);
        screen.addObject("myTickets", myTickets);

        return screen;
    }

    private ModelAndView getWelcomeScreenForGuest() {
        final ModelAndView screen = ScreenManager.get(Screen.HOME_GUEST);

        final UserLogin login = new UserLogin();
        screen.addObject("login", login);

        return screen;
    }

}